package org.bozo.im.service.protocols.xmpp.stanza.processor.roster;

import java.io.IOException;

import org.bozo.im.common.MessageType;
import org.bozo.im.common.types.Protocol;
import org.bozo.im.service.Constants;
import org.bozo.im.service.IMService;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.stanza.Stanza;
import org.bozo.im.service.protocols.xmpp.stanza.processor.StanzaProcessor;
import org.bozo.im.service.protocols.xmpp.stanza.task.activity.UpdateContactsTask;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

public class ItemStanzaProcessor extends StanzaProcessor {

	private static ItemStanzaProcessor mInstance;

	private ItemStanzaProcessor() {}

	public static ItemStanzaProcessor getInstance() {
		if (mInstance == null)
			mInstance = new ItemStanzaProcessor();
		return mInstance;
	}

	@Override
	public Stanza getStanza() {
		return Stanza.ROSTER_ITEM;
	}

	@Override
	public void processStanza(XmlPullParser pParser, XMPPSession pSession, StanzaProcessor pParentProcessor) throws XmlPullParserException, IOException {

		// ---------------------------------------------------------------------------------------
		Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.processor.roster.ItemStanzaProcessor.processStanza ---------- IN");
		// ---------------------------------------------------------------------------------------

		String lCurrentName = getStanza().getName();

		Protocol lProtocol = pSession.getConfiguration().getProtocol();
		String lId = null;
		String lDisplayName = null;

		for (int i = 0; i < pParser.getAttributeCount(); i++) {

			String lAttributeName = pParser.getAttributeName(i);

			if (lAttributeName.equals("jid")) {
				lId = pParser.getAttributeValue(i);

			} else if (lAttributeName.equals("name")) {
				lDisplayName = pParser.getAttributeValue(i);

			}

		}

		IMService.getInstance().getRoster().addContact(lProtocol, lId, lDisplayName);
		
		pParser.next();

		while (!(pParser.getEventType() == XmlPullParser.END_TAG && pParser.getName().equals(lCurrentName))) {

			if (pParser.getEventType() == XmlPullParser.START_TAG) {

				if (pParser.getName().equals("group")) {
					//TODO lRawContact.getGroups().add(pParser.nextText());
				}

			}

			pParser.next();
		}

		pSession.getTaskProcessor().pushTask(new UpdateContactsTask("contact-list-" + MessageType.GET_ROSTER_RESPONSE));

		// ---------------------------------------------------------------------------------------
		Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.processor.roster.ItemStanzaProcessor.processStanza ---------- OUT");
		// ---------------------------------------------------------------------------------------

	}
}
